<?php


namespace Catmes\LayAdmin\Components;


use Catmes\LayAdmin\helpers\HtmlHelper;

class FormField
{
    const TYPE_UPLOAD = 'upload';
    protected $inputType;
    protected $field;
    protected $value;
    protected $inputHtml='';
    protected $labelHtml='';
    protected $url='';
    protected $btnId='';

    /* @var Form $form */
    protected $form;

    public function __construct($field='', $value=null){
        $this->field = $field;
        $this->value = $value;
    }

    protected static function divFormItem($content):string{
        return self::div($content, ['class'=>'layui-form-item']);
    }

    public function setForm(Form $form):self{
        $this->form = $form;
        return $this;
    }

    public function label($content, $options=[]):self
    {
        HtmlHelper::addCssClass($options, ['layui-form-label']);
        $this->labelHtml = HtmlHelper::label($content, null, $options);
        return $this;
    }

    protected static function divInputInline($content):string{
        return self::div($content, ['class'=>'layui-input-inline']);
    }
    protected static function divInline($content):string{
        return self::div($content, ['class'=>'layui-inline']);
    }

    protected static function divInputBlock($content):string{
        return self::div($content, ['class'=>'layui-input-block']);
    }

    // "like[write]": true //复选框选中状态
    public function textInput($options = []): self
    {
        HtmlHelper::addCssClass($options, ['layui-input']);
        $inputHtml = HtmlHelper::textInput($this->field, $this->value,$options);
        $this->inputHtml = self::divInputBlock($inputHtml);
        return $this;
    }

    public function passwordInput($options = []): self
    {
        HtmlHelper::addCssClass($options, ['layui-input']);
        $inputHtml = HtmlHelper::passwordInput($this->field, $this->value, $options);
        $this->inputHtml = self::divInputBlock($inputHtml);
        return $this;
    }

    public function textarea($options=[]):self{
        HtmlHelper::addCssClass($options, ['layui-textarea']);
        $inputHtml = HtmlHelper::textarea($this->field, $this->value, $options);
        $this->inputHtml = self::divInputBlock($inputHtml);
        return $this;
    }

    public function uploadInput($uploadUrl, $options=[]):self{
        $this->inputType = self::TYPE_UPLOAD;
        $this->url = $uploadUrl;
        $this->btnId = "btn_id".mt_rand(11111,99999);
        if($this->form){
            $this->form->addModule("upload");
            $this->form->addJs($this->getUploadJs());
        }
        return $this->textInput($options);
    }

    protected function getUploadJs():string{
        $tpl = Template::getInstance();
        $csrfTokenField = $tpl->getCsrfTokenField();
        $csrfToken = $tpl->getCsrfToken();
        $formFilterId = $this->form->getFilterId();
        return <<<UPLOADJS
//执行实例
  var uploadInst = upload.render({
    elem: '#{$this->btnId}' //绑定元素
    ,url: '{$this->url}' //上传接口
    ,accept: 'file'
    ,data:{{$csrfTokenField}:"{$csrfToken}"}
    ,done: function(res){
        layer.msg(res.msg)
        if(res.code===200){
            form.val('{$formFilterId}', {{$this->field}:res.data.src})
        }
        console.log(res)
    }
    ,error: function(){
        layer.msg("上传错误，请稍候重试")
    }
  });
UPLOADJS;

    }

    public function hide():self{
        $this->inputHtml = HtmlHelper::hiddenInput($this->field, $this->value);
        return $this;
    }

    /**
     * 开关输入框
     * Form::getJsValue() 方法无法取值。慎用！！ "form.val('{$formFilterId}')";
     * $this->switchInput("开|关",['lay-filter'=>'switch_upload'])
     * "form.on('switch(switch_upload)', function (data){ var isCheck = this.checked ? 1 : 0;});"
     * @param string $layText 示例： "开|关"
     * @return $this
     */
    public function switchInput(string $layText, $options=[]):self{
        $options = array_merge(['lay-skin'=>'switch', 'lay-text'=>$layText],$options);
        $inputHtml = HtmlHelper::input('checkbox', $this->field, $this->value, $options);
        $this->inputHtml = self::divInputBlock($inputHtml);
        return $this;
    }

    public function radioList($items, $options=[]):self{
        HtmlHelper::addCssClass($options, ['layui-input']);
        $inputHtml = '';
        foreach ($items as $value => $title){
            $opts = ['title'=>$title];
            if($this->value==$value){
                $opts['checked'] = "";
            }
            $inputHtml .= HtmlHelper::input('radio', $this->field, $value,$opts);
        }
//        $inputHtml = HtmlHelper::radioList($this->field, $this->value, $items);

        $this->inputHtml = self::divInputBlock($inputHtml);
        return $this;
    }

    public function selectList($items, $options=[]):self{
//        HtmlHelper::addCssClass($options, ['layui-input']);
        $inputHtml = "<select name=\"{$this->field}\" lay-filter='selectFid'>"; // HtmlHelper::dropDownList($this->field, $this->value, $items, $options);
        foreach ($items as $key => $title){
            $itemOpts=['value'=>$key];
            if($this->value==$key){
                $itemOpts['selected'] = "\"\"";
            }
            $inputHtml .= HtmlHelper::tag('option', $title, $itemOpts);
//            $select = $this->value==$key ? "select=\"\"" : '';
//            $inputHtml .= "<option class=\"layui-input\" value=\"{$key}\" {$select}>{$title}</option>";
        }
        $inputHtml .= "</select>";
        $this->inputHtml = self::divInputBlock($inputHtml);
        return $this;
    }

    public function submit($text='提交',$options=[]):self{
        $defs = ['class'=>'layui-btn', 'lay-submit'=>'', 'lay-filter'=>'lay-submit-filter-id'];
        $options = array_merge($defs, $options);
        $submitBtnHtml = HtmlHelper::button($text,$options);
        $this->inputHtml = self::divInputBlock($submitBtnHtml);
        return $this;
    }

    public function render():string{
        if($this->inputType==self::TYPE_UPLOAD){
            $divInput = self::divInline($this->labelHtml.$this->inputHtml);

            $uploadBtn = HtmlHelper::button("上传",['class'=>"layui-btn",'id'=>$this->btnId]);
            $divBtn = self::divInline($uploadBtn);

            return self::divFormItem($divInput.$divBtn);
        }
        return self::divFormItem($this->labelHtml.$this->inputHtml);
    }

    public function __toString(){
        return $this->render();
    }

    protected static function div($content, $options=[]):string{
        return HtmlHelper::tag('div', $content, $options);
    }


}



//
//
//<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
//            <legend>表单集合演示</legend>
//        </fieldset>
//
//        <form class="layui-form" action="">
//            <div class="layui-form-item">
//                <label class="layui-form-label">单行输入框</label>
//                <div class="layui-input-block">
//                    <input type="text" name="title" lay-verify="title" autocomplete="off" placeholder="请输入标题" class="layui-input">
//                </div>
//            </div>
//            <div class="layui-form-item">
//                <label class="layui-form-label">验证必填项</label>
//                <div class="layui-input-block">
//                    <input type="text" name="username" lay-verify="required" lay-reqtext="用户名是必填项，岂能为空？" placeholder="请输入" autocomplete="off" class="layui-input">
//                </div>
//            </div>
//
//            <div class="layui-form-item">
//                <div class="layui-inline">
//                    <label class="layui-form-label">验证手机</label>
//                    <div class="layui-input-inline">
//                        <input type="tel" name="phone" lay-verify="required|phone" autocomplete="off" class="layui-input">
//                    </div>
//                </div>
//                <div class="layui-inline">
//                    <label class="layui-form-label">验证邮箱</label>
//                    <div class="layui-input-inline">
//                        <input type="text" name="email" lay-verify="email" autocomplete="off" class="layui-input">
//                    </div>
//                </div>
//            </div>
//
//            <div class="layui-form-item">
//                <div class="layui-inline">
//                    <label class="layui-form-label">多规则验证</label>
//                    <div class="layui-input-inline">
//                        <input type="text" name="number" lay-verify="required|number" autocomplete="off" class="layui-input">
//                    </div>
//                </div>
//                <div class="layui-inline">
//                    <label class="layui-form-label">验证日期</label>
//                    <div class="layui-input-inline">
//                        <input type="text" name="date" id="date" lay-verify="date" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
//                    </div>
//                </div>
//                <div class="layui-inline">
//                    <label class="layui-form-label">验证链接</label>
//                    <div class="layui-input-inline">
//                        <input type="tel" name="url" lay-verify="url" autocomplete="off" class="layui-input">
//                    </div>
//                </div>
//            </div>
//
//            <div class="layui-form-item">
//                <label class="layui-form-label">验证身份证</label>
//                <div class="layui-input-block">
//                    <input type="text" name="identity" lay-verify="identity" placeholder="" autocomplete="off" class="layui-input">
//                </div>
//            </div>
//            <div class="layui-form-item">
//                <label class="layui-form-label">自定义验证</label>
//                <div class="layui-input-inline">
//                    <input type="password" name="password" lay-verify="pass" placeholder="请输入密码" autocomplete="off" class="layui-input">
//                </div>
//                <div class="layui-form-mid layui-word-aux">请填写6到12位密码</div>
//            </div>
//
//            <div class="layui-form-item">
//                <div class="layui-inline">
//                    <label class="layui-form-label">范围</label>
//                    <div class="layui-input-inline" style="width: 100px;">
//                        <input type="text" name="price_min" placeholder="￥" autocomplete="off" class="layui-input">
//                    </div>
//                    <div class="layui-form-mid">-</div>
//                    <div class="layui-input-inline" style="width: 100px;">
//                        <input type="text" name="price_max" placeholder="￥" autocomplete="off" class="layui-input">
//                    </div>
//                </div>
//            </div>
//
//            <div class="layui-form-item">
//                <label class="layui-form-label">单行选择框</label>
//                <div class="layui-input-block">
//                    <select name="interest" lay-filter="aihao">
//                        <option value=""></option>
//                        <option value="0">写作</option>
//                        <option value="1" selected="">阅读</option>
//                        <option value="2">游戏</option>
//                        <option value="3">音乐</option>
//                        <option value="4">旅行</option>
//                    </select>
//                </div>
//            </div>
//
//
//            <div class="layui-form-item">
//                <div class="layui-inline">
//                    <label class="layui-form-label">分组选择框</label>
//                    <div class="layui-input-inline">
//                        <select name="quiz">
//                            <option value="">请选择问题</option>
//                            <optgroup label="城市记忆">
//                                <option value="你工作的第一个城市">你工作的第一个城市</option>
//                            </optgroup>
//                            <optgroup label="学生时代">
//                                <option value="你的工号">你的工号</option>
//                                <option value="你最喜欢的老师">你最喜欢的老师</option>
//                            </optgroup>
//                        </select>
//                    </div>
//                </div>
//                <div class="layui-inline">
//                    <label class="layui-form-label">搜索选择框</label>
//                    <div class="layui-input-inline">
//                        <select name="modules" lay-verify="required" lay-search="">
//                            <option value="">直接选择或搜索选择</option>
//                            <option value="1">layer</option>
//                            <option value="2">form</option>
//                            <option value="3">layim</option>
//                            <option value="4">element</option>
//                            <option value="5">laytpl</option>
//                            <option value="6">upload</option>
//                            <option value="7">laydate</option>
//                            <option value="8">laypage</option>
//                            <option value="9">flow</option>
//                            <option value="10">util</option>
//                            <option value="11">code</option>
//                            <option value="12">tree</option>
//                            <option value="13">layedit</option>
//                            <option value="14">nav</option>
//                            <option value="15">tab</option>
//                            <option value="16">table</option>
//                            <option value="17">select</option>
//                            <option value="18">checkbox</option>
//                            <option value="19">switch</option>
//                            <option value="20">radio</option>
//                        </select>
//                    </div>
//                </div>
//            </div>
//
//            <div class="layui-form-item">
//                <label class="layui-form-label">联动选择框</label>
//                <div class="layui-input-inline">
//                    <select name="quiz1">
//                        <option value="">请选择省</option>
//                        <option value="浙江" selected="">浙江省</option>
//                        <option value="你的工号">江西省</option>
//                        <option value="你最喜欢的老师">福建省</option>
//                    </select>
//                </div>
//                <div class="layui-input-inline">
//                    <select name="quiz2">
//                        <option value="">请选择市</option>
//                        <option value="杭州">杭州</option>
//                        <option value="宁波" disabled="">宁波</option>
//                        <option value="温州">温州</option>
//                        <option value="温州">台州</option>
//                        <option value="温州">绍兴</option>
//                    </select>
//                </div>
//                <div class="layui-input-inline">
//                    <select name="quiz3">
//                        <option value="">请选择县/区</option>
//                        <option value="西湖区">西湖区</option>
//                        <option value="余杭区">余杭区</option>
//                        <option value="拱墅区">临安市</option>
//                    </select>
//                </div>
//                <div class="layui-form-mid layui-word-aux">此处只是演示联动排版，并未做联动交互</div>
//            </div>
//
//            <div class="layui-form-item">
//                <label class="layui-form-label">复选框</label>
//                <div class="layui-input-block">
//                    <input type="checkbox" name="like[write]" title="写作">
//                    <input type="checkbox" name="like[read]" title="阅读" checked="">
//                    <input type="checkbox" name="like[game]" title="游戏">
//                </div>
//            </div>
//
//            <div class="layui-form-item" pane="">
//                <label class="layui-form-label">原始复选框</label>
//                <div class="layui-input-block">
//                    <input type="checkbox" name="like1[write]" lay-skin="primary" title="写作" checked="">
//                    <input type="checkbox" name="like1[read]" lay-skin="primary" title="阅读">
//                    <input type="checkbox" name="like1[game]" lay-skin="primary" title="游戏" disabled="">
//                </div>
//            </div>
//
//            <div class="layui-form-item">
//                <label class="layui-form-label">开关-默认关</label>
//                <div class="layui-input-block">
//                    <input type="checkbox" name="close" lay-skin="switch" lay-text="ON|OFF">
//                </div>
//            </div>
//            <div class="layui-form-item">
//                <label class="layui-form-label">开关-默认开</label>
//                <div class="layui-input-block">
//                    <input type="checkbox" checked="" name="open" lay-skin="switch" lay-filter="switchTest" lay-text="ON|OFF">
//                </div>
//            </div>
//            <div class="layui-form-item">
//                <label class="layui-form-label">单选框</label>
//                <div class="layui-input-block">
//                    <input type="radio" name="sex" value="男" title="男" checked="">
//                    <input type="radio" name="sex" value="女" title="女">
//                    <input type="radio" name="sex" value="禁" title="禁用" disabled="">
//                </div>
//            </div>
//            <div class="layui-form-item layui-form-text">
//                <label class="layui-form-label">普通文本域</label>
//                <div class="layui-input-block">
//                    <textarea placeholder="请输入内容" class="layui-textarea"></textarea>
//                </div>
//            </div>
//            <!--<div class="layui-form-item layui-form-text">
//              <label class="layui-form-label">编辑器</label>
//              <div class="layui-input-block">
//                <textarea class="layui-textarea layui-hide" name="content" lay-verify="content" id="LAY_demo_editor"></textarea>
//              </div>
//            </div>-->
//            <div class="layui-form-item">
//                <div class="layui-input-block">
//                    <button class="layui-btn" lay-submit="" lay-filter="demo1">立即提交</button>
//                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
//                </div>
//            </div>
//        </form>
//
//        <!-- 示例-970 -->
//        <ins class="adsbygoogle" style="display:inline-block;width:970px;height:90px" data-ad-client="ca-pub-6111334333458862" data-ad-slot="3820120620"></ins>
//
//        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
//            <legend>初始赋值演示</legend>
//        </fieldset>
//
//        <form class="layui-form" action="" lay-filter="example">
//            <div class="layui-form-item">
//                <label class="layui-form-label">输入框</label>
//                <div class="layui-input-block">
//                    <input type="text" name="username" lay-verify="title" autocomplete="off" placeholder="请输入标题" class="layui-input">
//                </div>
//            </div>
//            <div class="layui-form-item">
//                <label class="layui-form-label">密码框</label>
//                <div class="layui-input-block">
//                    <input type="password" name="password" placeholder="请输入密码" autocomplete="off" class="layui-input">
//                </div>
//            </div>
//
//            <div class="layui-form-item">
//                <label class="layui-form-label">选择框</label>
//                <div class="layui-input-block">
//                    <select name="interest" lay-filter="aihao">
//                        <option value=""></option>
//                        <option value="0">写作</option>
//                        <option value="1">阅读</option>
//                        <option value="2">游戏</option>
//                        <option value="3">音乐</option>
//                        <option value="4">旅行</option>
//                    </select>
//                </div>
//            </div>
//
//            <div class="layui-form-item">
//                <label class="layui-form-label">复选框</label>
//                <div class="layui-input-block">
//                    <input type="checkbox" name="like[write]" title="写作">
//                    <input type="checkbox" name="like[read]" title="阅读">
//                    <input type="checkbox" name="like[daze]" title="发呆">
//                </div>
//            </div>
//
//            <div class="layui-form-item">
//                <label class="layui-form-label">开关</label>
//                <div class="layui-input-block">
//                    <input type="checkbox" name="close" lay-skin="switch" lay-text="ON|OFF">
//                </div>
//            </div>
//
//            <div class="layui-form-item">
//                <label class="layui-form-label">单选框</label>
//                <div class="layui-input-block">
//                    <input type="radio" name="sex" value="男" title="男" checked="">
//                    <input type="radio" name="sex" value="女" title="女">
//                </div>
//            </div>
//            <div class="layui-form-item layui-form-text">
//                <label class="layui-form-label">文本域</label>
//                <div class="layui-input-block">
//                    <textarea placeholder="请输入内容" class="layui-textarea" name="desc"></textarea>
//                </div>
//            </div>
//
//            <div class="layui-form-item">
//                <div class="layui-input-block">
//                    <button class="layui-btn" lay-submit="" lay-filter="demo1">立即提交</button>
//                </div>
//            </div>
//        </form>
//
//
//
//
//
//        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
//            <legend>方框风格的表单集合</legend>
//        </fieldset>
//        <form class="layui-form layui-form-pane" action="">
//            <div class="layui-form-item">
//                <label class="layui-form-label">长输入框</label>
//                <div class="layui-input-block">
//                    <input type="text" name="title" autocomplete="off" placeholder="请输入标题" class="layui-input">
//                </div>
//            </div>
//            <div class="layui-form-item">
//                <label class="layui-form-label">短输入框</label>
//                <div class="layui-input-inline">
//                    <input type="text" name="username" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
//                </div>
//            </div>
//
//            <div class="layui-form-item">
//                <div class="layui-inline">
//                    <label class="layui-form-label">日期选择</label>
//                    <div class="layui-input-block">
//                        <input type="text" name="date" id="date1" autocomplete="off" class="layui-input">
//                    </div>
//                </div>
//                <div class="layui-inline">
//                    <label class="layui-form-label">行内表单</label>
//                    <div class="layui-input-inline">
//                        <input type="text" name="number" autocomplete="off" class="layui-input">
//                    </div>
//                </div>
//            </div>
//            <div class="layui-form-item">
//                <label class="layui-form-label">密码</label>
//                <div class="layui-input-inline">
//                    <input type="password" name="password" placeholder="请输入密码" autocomplete="off" class="layui-input">
//                </div>
//                <div class="layui-form-mid layui-word-aux">请务必填写用户名</div>
//            </div>
//
//            <div class="layui-form-item">
//                <div class="layui-inline">
//                    <label class="layui-form-label">范围</label>
//                    <div class="layui-input-inline" style="width: 100px;">
//                        <input type="text" name="price_min" placeholder="￥" autocomplete="off" class="layui-input">
//                    </div>
//                    <div class="layui-form-mid">-</div>
//                    <div class="layui-input-inline" style="width: 100px;">
//                        <input type="text" name="price_max" placeholder="￥" autocomplete="off" class="layui-input">
//                    </div>
//                </div>
//            </div>
//
//            <div class="layui-form-item">
//                <label class="layui-form-label">单行选择框</label>
//                <div class="layui-input-block">
//                    <select name="interest" lay-filter="aihao">
//                        <option value=""></option>
//                        <option value="0">写作</option>
//                        <option value="1" selected="">阅读</option>
//                        <option value="2">游戏</option>
//                        <option value="3">音乐</option>
//                        <option value="4">旅行</option>
//                    </select>
//                </div>
//            </div>
//
//            <div class="layui-form-item">
//                <label class="layui-form-label">行内选择框</label>
//                <div class="layui-input-inline">
//                    <select name="quiz1">
//                        <option value="">请选择省</option>
//                        <option value="浙江" selected="">浙江省</option>
//                        <option value="你的工号">江西省</option>
//                        <option value="你最喜欢的老师">福建省</option>
//                    </select>
//                </div>
//                <div class="layui-input-inline">
//                    <select name="quiz2">
//                        <option value="">请选择市</option>
//                        <option value="杭州">杭州</option>
//                        <option value="宁波" disabled="">宁波</option>
//                        <option value="温州">温州</option>
//                        <option value="温州">台州</option>
//                        <option value="温州">绍兴</option>
//                    </select>
//                </div>
//                <div class="layui-input-inline">
//                    <select name="quiz3">
//                        <option value="">请选择县/区</option>
//                        <option value="西湖区">西湖区</option>
//                        <option value="余杭区">余杭区</option>
//                        <option value="拱墅区">临安市</option>
//                    </select>
//                </div>
//            </div>
//            <div class="layui-form-item" pane="">
//                <label class="layui-form-label">开关-开</label>
//                <div class="layui-input-block">
//                    <input type="checkbox" checked="" name="open" lay-skin="switch" lay-filter="switchTest" title="开关">
//                </div>
//            </div>
//            <div class="layui-form-item" pane="">
//                <label class="layui-form-label">单选框</label>
//                <div class="layui-input-block">
//                    <input type="radio" name="sex" value="男" title="男" checked="">
//                    <input type="radio" name="sex" value="女" title="女">
//                    <input type="radio" name="sex" value="禁" title="禁用" disabled="">
//                </div>
//            </div>
//            <div class="layui-form-item layui-form-text">
//                <label class="layui-form-label">文本域</label>
//                <div class="layui-input-block">
//                    <textarea placeholder="请输入内容" class="layui-textarea"></textarea>
//                </div>
//            </div>
//            <div class="layui-form-item">
//                <button class="layui-btn" lay-submit="" lay-filter="demo2">跳转式提交</button>
//            </div>
//        </form>
//
//
//
//
//
//<script>
//layui.use(['form', 'layedit', 'laydate',
//    'element','upload'
//], function () {
//
//    var $ = layui.jquery,
//            element = layui.element;
//    var form = layui.form
//            , layer = layui.layer
//            , layedit = layui.layedit
//            , laydate = layui.laydate;
//
//
//        /**
//         * 初始化表单，要加上，不然刷新部分组件可能会不加载
//         */
//        form.render();
//
//        //日期
//        laydate.render({
//            elem: '#date'
//        });
//        laydate.render({
//            elem: '#date1'
//        });
//
//        //创建一个编辑器
//        var editIndex = layedit.build('LAY_demo_editor');
//
//        //自定义验证规则
//        form.verify({
//            title: function (value) {
//        if (value.length < 5) {
//            return '标题至少得5个字符啊';
//        }
//    }
//            , pass: [
//                /^[\S]{6,12}$/
//                , '密码必须6到12位，且不能出现空格'
//            ]
//            , content: function (value) {
//        layedit.sync(editIndex);
//    }
//        });
//
//        //监听指定开关
//        form.on('switch(switchTest)', function (data) {
//            layer.msg('开关checked：' + (this.checked ? 'true' : 'false'), {
//                offset: '6px'
//            });
//            layer.tips('温馨提示：请注意开关状态的文字可以随意定义，而不仅仅是ON|OFF', data.othis)
//        });
//
//        //监听提交
//        form.on('submit(demo1)', function (data) {
//            layer.alert(JSON.stringify(data.field), {
//                title: '最终的提交信息'
//            })
//            return false;
//        });
//
//        //表单初始赋值
//        form.val('example', {
//            "username": "贤心" // "name": "value"
//            , "password": "123456"
//            , "interest": 1
//            , "like[write]": true //复选框选中状态
//            , "close": true //开关状态
//            , "sex": "女"
//            , "desc": "我爱 layui"
//        })
//    });
//</script>
